package com.qfedu.dao.impl;

import com.qfedu.dao.AddressDao;
import com.qfedu.pojo.Address;
import com.qfedu.utils.DataSourceUtils;
import com.qfedu.utils.TxUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * 创建者: QF-SUN
 * 创建时间: 2023/4/6 9:31
 * 描述:
 */
public class AddressDaoImpl implements AddressDao {

    QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());

    @Override
    public List<Address> selectAddresses(int userId) {
        String sql = "select * from tb_address where uid = ?";
        try {
            List<Address> addressList = qr.query(sql, new BeanListHandler<>(Address.class), userId);
            return addressList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void insert(Address address) {
        String sql = "INSERT INTO `tb_address`(`id`,`detail`,`name`,`phone`,`uid`,`level`)VALUES(null, ?,?,?,?,?)";
        try {
            qr.update(sql, address.getDetail(), address.getName(), address.getPhone(), address.getUid(), address.getLevel());
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("新增地址失败");
        }
    }

    @Override
    public void deleteById(String id) {
        String sql = "delete from tb_address where id = ?";
        try {
            qr.update(sql, id);
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("修改地址失败");
        }
    }

    @Override
    public void update(Address address) {
        String sql = "UPDATE `tb_address` SET `detail` = ?,`name` = ?,`phone` = ?,`uid` = ?, `level` =? WHERE `id` = ?";
        try {
            qr.update(sql, address.getDetail(), address.getName(), address.getPhone(), address.getUid(), address.getLevel(), address.getId());
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("修改地址失败");
        }
    }

    @Override
    public void setNotDefault(int uid) {
        QueryRunner qr = new QueryRunner();
        String sql = "UPDATE `tb_address` SET `level` =0 WHERE uid = ?";
        try {
            qr.update(TxUtils.getConn(),sql, uid);
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("修改地址失败");
        }
    }

    @Override
    public void setDefault(int id) {
        QueryRunner qr = new QueryRunner();
        String sql = "UPDATE `tb_address` SET `level` = 1 WHERE id = ?";
        try {
            qr.update(TxUtils.getConn(), sql, id);
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("修改地址失败");
        }
    }
}
